import { Request, Response } from "express";
import * as RoleService from "../services/role.service";
import { prisma } from "../prisma/client";
import { ResponseUtil } from "../utils/response.util";

// 获取所有角色
export const getAllRoles = async (req: Request, res: Response) => {
  try {
    const page = Number(req.query.page);
    const pageSize = Number(req.query.pageSize);
    const options = req.body;
    const roles = await RoleService.getAllRoles(page, pageSize, options);
    ResponseUtil.success(res, roles);
  } catch (err) {
    ResponseUtil.error(res, err, "获取角色失败");
  }
};

// 获取角色详情
export const getRoleById = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const role = await RoleService.getRoleById(id);
    if (!role) return ResponseUtil.error(res, null, "角色不存在");
    ResponseUtil.success(res, null, "查询角色成功");
  } catch (err) {
    ResponseUtil.error(res, err, "获取角色失败");
  }
};

// 创建角色
export const createRole = async (req: Request, res: Response) => {
  try {
    const role = await RoleService.createRole(req.body);
    ResponseUtil.success(res, role);
  } catch (err) {
    ResponseUtil.error(res, err, "创建角色失败");
  }
};

// 更新角色
export const updateRole = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const role = await RoleService.updateRole(id, req.body);
    ResponseUtil.success(res, role);
  } catch (err) {
    ResponseUtil.error(res, err, "更新角色失败");
  }
};

// 删除角色
export const deleteRole = async (req: Request, res: Response) => {
  try {
    const id = Number(req.params.id);
    const deleteOne = await RoleService.deleteRole(id);
    ResponseUtil.success(res, deleteOne, "删除成功");
  } catch (err) {
    ResponseUtil.success(res, err, "删除角色失败");
  }
};

// 给角色绑定权限
export const assignPermissionsToRole = async (req: Request, res: Response) => {
  const roleId = parseInt(req.params.roleId);
  const { permissionIds } = req.body;
  if (!Array.isArray(permissionIds)) {
    ResponseUtil.error(res, null, "权限参数需要为列表");
  }
  const updateRole = await RoleService.assignPermissionsToRole(
    roleId,
    permissionIds
  );
  ResponseUtil.success(res, updateRole, "权限绑定成功");
};

// 查询角色权限
export const getRolePermissions = async (req: Request, res: Response) => {
  const roleId = parseInt(req.params.roleId);
  const role = await prisma.role.findUnique({
    where: {
      id: roleId,
    },
    include: {
      rolePermissions: {
        include: {
          permission: true,
        },
      },
    },
  });
  if (!role) return ResponseUtil.error(res, null, "不存在该角色");
  ResponseUtil.success(
    res,
    role.rolePermissions.map((rp) => rp.permission),
    "查询角色权限成功"
  );
};
